import { defineStore } from 'pinia'
import {
  getVerifyCode as getVerifyCode,
  loginByPhone, 
  loginByPassword

} from '/@/api/loginApi'
import { setToken, clearToken, getToken } from '/@/utils/auth'
import { loginState } from './types'
import { resolveEnvPrefix } from 'vite'

export const useLoginStore = defineStore('login', {
  state: (): loginState => ({
    accesstoken: getToken() as string | undefined,
    studentInfo: undefined,
    cartCount: 0
  }),
  getters: {
    userProfile(state: loginState): loginState {
      return { ...state }
    },
    // accesstoken(state: loginState): string | undefined {

    //   if(state.accesstoken === undefined) {
    //     const lsToken =  getToken();
    //     state.accesstoken = lsToken?lsToken:undefined; 
    //   }

    //   return state.accesstoken;
    // },
    cartCount: (state: loginState) => state.cartCount,

    isLogin :(state: loginState) => {
      return !!state.accesstoken;
    }
  },
  actions: {
    // 
    getAccesstoken() {
      if(!this.accesstoken) {
        const lsToken =  getToken();
        this.accesstoken = lsToken?lsToken:undefined; 
      }
      return this.accesstoken;
    },

    // 异步调用接口获取验证码
    async getVerifyCode(phone: string) {
      await getVerifyCode({phone:phone}).then((res) =>{
        console.log(res);
      }).catch((err) =>{throw err; });

      return phone
    },

    async loginByCode(loginForm) { // 手机验证码登录
      return await loginByPhone(loginForm).then((result) => {
        //console.log(result);
        if(result?.accesstoken) {
          this.accesstoken = result?.accesstoken;
          setToken(result?.accesstoken);
        } else {
          clearToken();
          this.accesstoken = undefined;
        }
        //return result;
      });
    },
    async loginByPassword(userName:string, password:string) { // 账号密码登录
      setToken('');
    },

    async logOut() { // 退出登录
      // 调起接口
      
    },
  },
})
